<template>
  <view class="login-container">
    <view class="logo">
      <image src="/static/logo.png" mode="aspectFit"></image>
    </view>
    
    <view class="welcome">
      <text class="title">欢迎使用照片记忆</text>
      <text class="subtitle">登录后即可使用完整功能</text>
    </view>
    
    <button 
      class="login-btn"
      type="primary"
      @tap="handleLogin"
    >立即登录</button>
    
    <view class="privacy-tip">
      登录即表示同意
      <view class="link-container" @tap="navigateTo('/pages/my/privacy')">
        <text class="link">《隐私政策》</text>
      </view>
      和
      <view class="link-container" @tap="navigateTo('/pages/my/terms')">
        <text class="link">《用户协议》</text>
      </view>
    </view>
  </view>
</template>

<script>
import { wxMiniLogin } from '@/api/auth'
import { getUserInfo } from '@/api/user'
import globalState from '@/utils/globalState.js'

export default {
  data() {
    return {
      loading: false
    }
  },
  
  methods: {
    // 获取微信登录code
    async getWxLoginCode() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: (res) => {
            resolve(res.code)
          },
          fail: (err) => {
            reject(err)
          }
        })
      })
    },
    
    // 处理登录
    async handleLogin() {
      console.log('handleLogin被点击，调用loginWithWeChat')
      return this.loginWithWeChat()
    },
    
    navigateTo(url) {
      uni.navigateTo({ url })
    },

    // 微信登录
    async loginWithWeChat() {
      try {
        this.loading = true
        
        // 设置手动登录标志
        console.log('设置手动登录标志...');
        globalState.setManualLogin(true)
        // 使用本地存储备份标志，确保跨文件访问
        uni.setStorageSync('isManualLogin', true)
        
        // 获取微信登录code
        const { code } = await uni.login()
        if (!code) {
          throw new Error('获取微信登录凭证失败')
        }
        
        // 调用后端登录接口
        const res = await wxMiniLogin({ code })
        
        // 处理登录响应
        await this.handleLoginResponse(res)
        
        uni.showToast({
          title: '登录成功',
          icon: 'success'
        })
        
        // 登录成功后的重定向
        setTimeout(() => {
          this.redirectAfterLogin()
        }, 1500)
      } catch (error) {
        console.error('登录失败:', error)
        uni.showToast({
          title: '登录失败: ' + (error.message || '请稍后再试'),
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },

    // 处理登录响应
    async handleLoginResponse(res) {
      console.log('登录响应:', res)
      // 提取并保存token
      let token = null
      
      // 判断data的类型并提取token
      if (res && res.data) {
        if (typeof res.data === 'string') {
          // 如果data直接是token字符串
          token = res.data
        } else if (res.data.token) {
          // 如果token是data对象的属性
          token = res.data.token
        }
      }
      
      if (!token) {
        console.error('无法从响应中提取token:', res)
        throw new Error('登录成功但无法获取token')
      }
      
      console.log('成功提取token:', token.substring(0, 8) + '...')
      this.$store.commit('SET_TOKEN', token)
      
      // 直接保存到storage，确保token被存储
      console.log('直接保存token到storage');
      uni.setStorageSync('token', token);
      
      // 设置登录状态
      uni.setStorageSync('isLogin', true);
      
      // 获取用户信息
      try {
        return this.$store.dispatch('fetchUserInfo')
      } catch (error) {
        console.error('登录成功但获取用户信息失败:', error);
        // 即使获取用户信息失败，仍然返回成功，因为token已获取
        return Promise.resolve();
      }
    },

    redirectAfterLogin() {
      const pages = getCurrentPages()
      if (pages.length > 1) {
        uni.navigateBack()
      } else {
        uni.switchTab({
          url: '/pages/index/index'
        })
      }
    }
  }
}
</script>

<style>
.login-container {
  min-height: 100vh;
  padding: 60rpx 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
}

.logo {
  margin: 60rpx 0;
}

.logo image {
  width: 200rpx;
  height: 200rpx;
}

.welcome {
  text-align: center;
  margin-bottom: 80rpx;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.subtitle {
  font-size: 28rpx;
  color: #999;
}

.login-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 45rpx;
  font-size: 32rpx;
  margin-bottom: 40rpx;
}

.privacy-tip {
  font-size: 24rpx;
  color: #999;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.link-container {
  display: inline-flex;
  padding: 6rpx 10rpx;
  margin: 0 4rpx;
}

.link {
  color: #3a8838;
}

.link-container:active {
  opacity: 0.7;
  background-color: rgba(58, 136, 56, 0.05);
  border-radius: 4rpx;
}
</style> 